﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Traceability_2203.Api.Application.Commands.USer;
using Traceability_2203.Api.Application.Commands.USers;
using Traceability_2203.Api.Common;
using Traceability_2203.Common.Domain;
using Traceability_2203.Common.Dto;
using Traceability_2203.Common.Infrastructure.interFaces;
using Traceability_2203.Common.Infrastructure.Repostories;
using Traceability_2203.Common.Migrations;
using Traceability_2203.Enum;

namespace Traceability_2203.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserController : ControllerBase
    {

        private readonly IMediator _mediator;
        private readonly IConfiguration _configuration;
        private readonly NLog.ILogger _logger =  NLog.LogManager.GetCurrentClassLogger();

        private readonly ILogger<UserController> logger;
   private readonly IdentityService _identityService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator"></param>
        public UserController(IMediator mediator, IConfiguration configuration, ILogger<UserController> logger, IdentityService _identityService)
        {
            _mediator = mediator;
            _configuration = configuration;
            this.logger = logger;  
            this._identityService = _identityService;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        [AllowAnonymous]
         public async Task<Reult> Adduse(USersCreateCommand cmd)
        {
            return await _mediator.Send(cmd);



        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>

        [HttpPost]
        public async Task<Reult> Update(UserupdateCommand cmd)
        {
            return await _mediator.Send(cmd);
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Reult<List<UsersDto>>> Html(UserSearchcommand cmd)
        {

            _logger.Info("sddfsfsdfsd");
            logger.LogInformation("111111111111111111111");

            var a = _identityService.userid;
            var b = _identityService.password;

            var username = User.FindFirst("username").Value;
            var user = User.FindFirst("UserId").Value;
     

            return await _mediator.Send(cmd);


        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<string> Login(string name, string pwd)
        {

            var Token = CreateTokenString(name);
            return Token;

            //生成Tokoen 令牌



        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString(string username)
        {
            //读取配置文件
            var jwtSettings = _configuration.GetSection("JWT").Get<jwtSttings>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SecurityKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //Claims是指用户的身份信息，例如用户名、角色、权限等，它们通常被包含在一个ClaimsPrincipal对象中。
            var claims = new[]
            {
         new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
         new Claim("Email","pmandy@163.com"),
         new Claim("Phone","123456"),
         new Claim("UserId","1"),
         new Claim("Username",username),
     };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,//发行者
                audience: jwtSettings.Audience,//受众
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }



        [HttpGet]
        public async Task<UsersDto>GetToken(string token)
        {
            //替换
            token = token.Replace("Bearer", "");
            //声明jwt handler
            var jwtHnadler = new JwtSecurityTokenHandler();
            //读取token 获取载核
            var payload= jwtHnadler.ReadJwtToken(token).Payload;
            //载荷里面 有
            var calsims = payload.Claims;
            var userid = calsims.Where(x => x.Type == "Userid").FirstOrDefault();
            var username = calsims.Where(x => x.Type == "username").FirstOrDefault();

            var result = new UsersDto()
            {
                Userid = int.Parse(userid.Value)
                ,USerName= username.Value
            };

            return result;

        }



        //[HttpPost]
        //public async Task<Reult<List<UsersDto>>> Seruser(UserupdateCommand cmd)
        //{

        //    var a = _identityService.userid;
        //    var b = _identityService.userid;

        //    var username = User.FindFirst("username").Value;
        //    var user = User.FindFirst("UserId").Value;
        //    return await _mediator.Send(cmd);




        //}


    }
}
